package com.share.wechat;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.share.R;
import com.share.wechat.bean.Share;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

/**
 *
 */
public class ShareDialogBuilder extends AlertDialog.Builder implements
        DialogInterface.OnCancelListener, DialogInterface.OnDismissListener {
    private Share mShare;
    private Activity mActivity;
    private AlertDialog mAlertDialog;

    private ShareDialogBuilder(@NonNull Activity context, @StyleRes int themeResId) {
        super(context, themeResId);
        mActivity = context;
        setTitle(null);
    }

    public static ShareBuilder with(Activity activity) {
        return with(activity, R.style.share_dialog);
    }

    public static ShareBuilder with(@NonNull Activity activity, @StyleRes int themeResId) {
        return new ShareBuilder(activity, themeResId);
    }

    private List<ShareItem> getAdapterData() {
        List<ShareItem> shareActions = new ArrayList<>();
        Share share = getShare();
        //1.朋友圈
        shareActions.add(new ShareItem(R.mipmap.ic_action_moments, R.string.platform_wechat_circle));

        //2.微信
        shareActions.add(new ShareItem(R.mipmap.ic_login_3party_wechat, R.string.platform_wechat));

        //0.新浪微博
//        shareActions.add(new ShareItem(R.mipmap.ic_login_3party_weibo, R.string.platform_sina));

        //3.QQ

        if (share.isShowDownload()) {
            //1.朋友圈
            shareActions.add(new ShareItem(R.mipmap.ic_download, R.string.platform_download));
        }


        //5.browser
//        shareActions.add(new ShareItem(R.mipmap.ic_action_browser, R.string.platform_browser));
//
//        //6.复制链接
//        shareActions.add(new ShareItem(R.mipmap.ic_action_url, R.string.platform_copy_link));
//
//        //7.更多
//        shareActions.add(new ShareItem(R.mipmap.ic_action_more, R.string.platform_more_option));

        return shareActions;
    }

    @SuppressWarnings("deprecation")
    @Override
    public AlertDialog create() {

        AlertDialog alertDialog = super.create();
        Window window = alertDialog.getWindow();

        if (window != null) {
            window.setGravity(Gravity.BOTTOM);
            WindowManager m = window.getWindowManager();
            Display d = m.getDefaultDisplay();
            WindowManager.LayoutParams p = window.getAttributes();
            p.width = d.getWidth();
            window.setAttributes(p);
        }
        this.mAlertDialog = alertDialog;
        return alertDialog;
    }

    @Override
    public AlertDialog.Builder setView(int layoutResId) {
        AlertDialog.Builder builder = super.setView(layoutResId);
        if (layoutResId == R.layout.dialog_share_main) {
            LayoutInflater inflater = LayoutInflater.from(getContext());
            View contentView = inflater.inflate(layoutResId, null, false);
            RecyclerView shareRecycle = (RecyclerView) contentView.findViewById(R.id.share_recycler);
            TextView tvCancel = (TextView) contentView.findViewById(R.id.tv_cancel);
            tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    cancelLoading();
                }
            });
            Share share = getShare();
            shareRecycle.setAdapter(new ShareActionAdapter(getAdapterData()));
            shareRecycle.setItemAnimator(new DefaultItemAnimator());
            shareRecycle.setLayoutManager(new GridLayoutManager(getContext(), share.isShowDownload() ? 3 : 2));
            builder.setView(contentView);
            builder.setOnCancelListener(this);
            builder.setOnDismissListener(this);
        }
        return builder;
    }

    public ShareDialogBuilder addShare(Share share) {
        this.mShare = share;
        return this;
    }

    public ShareDialogBuilder boundActivity(Activity activity) {
        this.mActivity = activity;
        return this;
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        hideWaitDialog();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        hideWaitDialog();
    }

    public void onItemClick(int position, ShareItem item) {
        Share share = getShare();
        //朋友圈
        if (item.iconId == R.mipmap.ic_action_moments) {
            if (!isInstallPackage("com.tencent.mm")) {
                Toast.makeText(mActivity, R.string.share_hint, Toast.LENGTH_SHORT).show();
                return;
            }
//                MProgressDialog.showProgress(mActivity, mActivity.getResources().getString(R.string.login_wechat_hint));
            OpenBuilder.with(platformActionListener, mActivity)
                    .useWechat()
                    .shareToWeiChatCircle(share);
            cancelLoading();
            //微信会话
        } else if (item.iconId == R.mipmap.ic_login_3party_wechat) {
            if (!isInstallPackage("com.tencent.mm")) {
                Toast.makeText(mActivity, R.string.share_hint, Toast.LENGTH_SHORT).show();
                return;
            }
//                MProgressDialog.showProgress(mActivity, mActivity.getResources().getString(R.string.login_wechat_hint));
            OpenBuilder.with(platformActionListener, mActivity)
                    .useWechat()
                    .shareToWeiChat(share);
            cancelLoading();
            //微博分享
        } else if (item.iconId == R.mipmap.ic_login_3party_weibo) {
//            if (appIsAvilible(mActivity, "com.sina.weibo")) {
//                Toast.makeText(mActivity, R.string.share_hint, Toast.LENGTH_SHORT).show();
//                return;
//            }
//                MProgressDialog.showProgress(mActivity, mActivity.getResources().getString(R.string.login_weibo_hint));
            OpenBuilder.with(platformActionListener, mActivity)
                    .useWeiBo()
                    .shareToWeiBo(share);
            cancelLoading();
            //QQ
        } else if (item.iconId == R.mipmap.ic_login_3party_qq) {
            if (appIsAvilible(mActivity, "com.tencent.mobileqq")) {
                Toast.makeText(mActivity, R.string.share_hint, Toast.LENGTH_SHORT).show();
                return;
            }
//                MProgressDialog.showProgress(mActivity, mActivity.getResources().getString(R.string.login_tencent_hint));
            OpenBuilder.with(platformActionListener, mActivity)
                    .useWechat()
                    .shareToQQ(share);
            cancelLoading();
        } else if (item.iconId == R.mipmap.ic_download) {
            if (null != listener) {
                listener.download();
            }
            cancelLoading();
        } else {
            showSystemShareOption(share.getTitle(), share.getUrl());
            cancelLoading();
        }
    }


    /**
     * 直接分享到微信回话
     */
    public void shareWechat() {
        Share share = getShare();
        OpenBuilder.with(platformActionListener, mActivity)
                .useWechat()
                .shareToWeiChat(share);


    }

    /**
     * 直接分享到微信朋友圈
     */
    public void shareWechatCircle() {
        Share share = getShare();
        OpenBuilder.with(platformActionListener, mActivity)
                .useWechat()
                .shareToWeiChatCircle(share);
    }


    private OnDownloadListener listener;


    public void setDownloadListener(OnDownloadListener l) {
        listener = l;
    }


    public interface OnDownloadListener {

        /**
         * 开始支付，用于显示load dialog
         */
        void download();

    }


    /**
     * hide waitDialog
     */
    private void hideWaitDialog() {

//        TipDialogUtils.showProgressDialog(mActivity, "正在处理");

    }

    public Share getShare() {
        return mShare;
    }

    /**
     * 调用系统安装的应用分享
     *
     * @param title title
     * @param url   url
     */
    private void showSystemShareOption(final String title, final String url) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "分享：" + title);
        intent.putExtra(Intent.EXTRA_TEXT, title + " " + url);
        getContext().startActivity(Intent.createChooser(intent, "选择分享"));
    }

//    @Override
//    public void onFailed() {
//        hideWaitDialog();
//        Toast.makeText(mActivity, R.string.share_hint, Toast.LENGTH_SHORT).show();
//    }
//
//    @Override
//    public void onSuccess() {
//        //调起第三方客户端
//        //        if (mAlertDialog != null && mAlertDialog.isShowing()) {
//        //            mAlertDialog.cancel();
//        //            //mAlertDialog.dismiss();
//        //        }
//    }

    /**
     * cancelLoading
     */
    public void cancelLoading() {
        if (mAlertDialog != null && mAlertDialog.isShowing()) {
            mAlertDialog.cancel();
            //mAlertDialog.dismiss();
        }
    }

    public static class ShareBuilder {
        private Activity activity;
        private int themeResId;
        private String title;
        private String summary;
        private String content;
        private String description;
        private String url;
        private int bitmapResID = R.mipmap.ic_action_moments;
        //是否显示下载
        private boolean isShowDownload = true;
        private long id;
        private int type;
        private String imageUrl;

        public ShareBuilder(Activity activity, int themeResId) {
            this.activity = activity;
            this.themeResId = themeResId;
        }

        public ShareBuilder isShowDownload(boolean isShowDownload) {
            this.isShowDownload = isShowDownload;
            return this;
        }


        public ShareBuilder id(long id) {
            this.id = id;
            return this;
        }


        public ShareBuilder type(int type) {
            this.type = type;
            return this;
        }

        public ShareBuilder title(String title) {
            this.title = title;
            return this;
        }

        public ShareBuilder content(String content) {
            this.content = content;
            this.summary = content;
            this.description = content;
            return this;
        }

        public ShareBuilder url(String url) {
            this.url = url;
            return this;
        }

        public ShareBuilder bitmapResID(int bitmapResID) {
            this.bitmapResID = bitmapResID;
            return this;
        }

        public ShareDialogBuilder build() {
            Share share = new Share();
            share.setTitle(title);
            share.setSummary(summary);
            share.setContent(content);
            share.setDescription(description);
            share.setUrl(url);
            share.setBitmapResID(bitmapResID);
            share.setImageUrl(imageUrl);
            share.setShowDownload(isShowDownload);
            share.setAppName("双重安培");
            share.setAppShareIcon(R.mipmap.ic_action_moments);

            ShareDialogBuilder builder = new ShareDialogBuilder(activity, themeResId);
            builder.mShare = share;

//            if (id > 0 && type >= 0) {
//                About.Share aboutShare = About.buildShare(id, type);
//                aboutShare.title = title;
//                aboutShare.content = content;
//                builder.mAboutShare = aboutShare;
//            }

            builder.setView(R.layout.dialog_share_main);
            return builder;
        }

        public ShareBuilder imageUrl(String imageUrl) {
            this.imageUrl = imageUrl;
            return this;
        }
    }

    private class ShareActionAdapter extends RecyclerView.Adapter<ViewHolder>
            implements View.OnClickListener {
        private List<ShareItem> mShareActions;

        ShareActionAdapter(List<ShareItem> shareActions) {
            this.mShareActions = shareActions;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            Context context = parent.getContext();
            View rootView = LayoutInflater.from(context).inflate(R.layout.dialog_share_item,
                    parent, false);
            ViewHolder viewHolder = new ViewHolder(rootView);
            viewHolder.mIvIcon.setOnClickListener(this);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            ShareItem shareAction = mShareActions.get(position);
            holder.itemView.setTag(shareAction);
            holder.mIvIcon.setImageResource(shareAction.iconId);
            holder.mTvName.setText(shareAction.nameId);
            holder.mIvIcon.setTag(holder);
        }

        @Override
        public int getItemCount() {
            return mShareActions == null ? 0 : mShareActions.size();
        }

        @Override
        public void onClick(View v) {
            try {
                ViewHolder viewHolder = (ViewHolder) v.getTag();
                int position = viewHolder.getAdapterPosition();
                ShareItem item = (ShareItem) viewHolder.itemView.getTag();
                onItemClick(position, item);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView mIvIcon;
        TextView mTvName;

        public ViewHolder(View itemView) {
            super(itemView);
            mIvIcon = itemView.findViewById(R.id.share_icon);
            mTvName = itemView.findViewById(R.id.share_name);
        }
    }

    private static class ShareItem {
        int iconId;
        int nameId;

        ShareItem(int iconId, int nameId) {
            this.iconId = iconId;
            this.nameId = nameId;
        }
    }

    final Handler showMsg = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Toast.makeText(mActivity, msg.obj.toString(), Toast.LENGTH_SHORT).show();
            return true;
        }
    });

    final PlatformActionListener platformActionListener = new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> stringObjectHashMap) {
//            Message msg = Message.obtain(showMsg);
//            hideWaitDialog();
//            msg.obj = "分享成功！";
//            msg.sendToTarget();
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            Message msg = Message.obtain(showMsg);
            hideWaitDialog();
            msg.obj = "好像出了错误";
            msg.sendToTarget();
        }

        @Override
        public void onCancel(Platform platform, int i) {
//            Message msg = Message.obtain(showMsg);
//            hideWaitDialog();
//            msg.obj = "取消了耶...";
//            msg.sendToTarget();
        }
    };


    /**
     * 判断app是否安装
     *
     * @param packageName
     * @return
     */
    public static boolean appIsAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }


    private static boolean isInstallPackage(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

}
